package com.ruoyi.social.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.Apps.Utils.SystemPointConfig;
import com.ruoyi.Apps.Utils.TikTokProductUrlParser;
import com.ruoyi.Apps.advice.I18ExceptionHandler;
import com.ruoyi.common.exception.I18nException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.points.domain.VideoPoints;
import com.ruoyi.points.service.IVideoPointsService;
import com.ruoyi.social.Enum.ProductStatusEnum;
import com.ruoyi.social.domain.*;
import com.ruoyi.social.service.*;
import com.ruoyi.social.view.RequestFullItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.social.mapper.SocialProductMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品数据Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-09-24
 */
@Service
public class SocialProductServiceImpl implements ISocialProductService 
{
    @Autowired
    private SocialProductMapper socialProductMapper;

    @Autowired
    private IVideoPointsService pointsService;

    @Autowired
    private SocialProcessorService processorService;

    @Autowired
    private ISocialProductUserService productUserService;

    @Autowired
    private ISocialShopService shopService;

    @Autowired
    private ISocialShopUserService shopUserService;

    @Autowired
    private ISocialProductTrendService productTrendService;

    @Autowired
    private ISocialVideoService videoService;

    @Autowired
    private ISocialKolService kolService;

    private static final Logger log = LoggerFactory.getLogger(SocialProductServiceImpl.class);
    /**
     * 查询商品数据
     * 
     * @param id 商品数据主键
     * @return 商品数据
     */
    @Override
    public SocialProduct selectSocialProductById(Long id)
    {
        return socialProductMapper.selectSocialProductById(id);
    }

    /**
     * 初始化数据
     *  SocialProduct 中的URL为 绝对URL 也就是不含 ? 之后的参数；保证所有用户输入的都是唯一商品URL
     *  SocialProductUser 中的URL的全部用户输入的URL，个性化URL
     *  SocialProduct 的status 属于商品级别 status；SocialProductUser的status是用户级别的status
     *  SocialProduct 的status只有第一次会更新 error 直到success结束；SocialProductUser的status是每次用户更新都会变更
     * @param url
     * @param channel
     */
    @Override
    @Transactional
    public void processorProductStart(String url, String channel) {
        Long userId = SecurityUtils.getUserId();
        VideoPoints points = pointsService.selectVideoPointsByUserId(userId);
        if (points.getPoints() < SystemPointConfig.PRODUCT_POINT) {
            throw new I18nException("point.insufficient");
        }

        TikTokProductUrlParser.TikTokProductInfo info = TikTokProductUrlParser.parseProductUrl(url);
        SocialProduct product = socialProductMapper.selectSocialProductByLink(info.getBaseUrl());
        SocialProductUser productUser;

        // 决定是复用还是新建：如果存在并且（今天已更新 或 status != success）则复用，否则新建
        boolean reuse = product != null &&
                (DateUtils.isSameDay(product.getProductInfoUpdateData(), new Date())
                        || !Objects.equals(product.getStatus(), ProductStatusEnum.success.toString()));

        if (reuse) {
            productUser = productUserService.checkSocialProductUser(userId, product, url);
            if ("true".equals(productUser.getParams().get("isnew"))) { changePoint(url, points); }
        } else {
            // 新建产品并扣分
            product = new SocialProduct();
            product.setProductLink(info.getBaseUrl());
            product.setProductOutid(info.getProductId());
            product.setStatus(ProductStatusEnum.start.toString());
            insertSocialProduct(product);

            productUser = productUserService.checkSocialProductUser(userId, product, info.getFullUrl());
            changePoint(url, points);
        }

        // 执行处理（外部 service 返回一个状态字符串）
        String resString = processorService.getFullRequest(url, channel, product.getId());
        if (resString == null) {
            // 防御性处理：避免 null 导致比较异常，按失败处理（可按你们业务调整）
            resString = ProductStatusEnum.fail.toString();
        }

        // 只有状态变化时更新 product（并记录更新时间）
        if (!Objects.equals(resString, product.getStatus())) {
            product.setStatus(resString);
            product.setProductInfoUpdateData(new Date());
            updateSocialProduct(product);
        }

        // 更新 productUser 状态（有变化才更新）
        if (productUser != null && !Objects.equals(resString, productUser.getStatus())) {
            productUser.setStatus(resString);
            productUserService.updateSocialProductUser(productUser);
        }
    }

    @Override
    @Transactional
    public void processorProductEnd(Long id, Long userId, JSONObject jsonObject) {
        SocialProduct product = selectSocialProductById(id);
        if(StringUtils.isNull(jsonObject) || StringUtils.isNull(product)) {
            log.warn("收到无效的数据：" + id + ",json->" +(StringUtils.isNull(jsonObject) ? "null": jsonObject.toJSONString()));
            return;
        }
        String status = jsonObject.getString("type");
        // 状态有效
        if (StringUtils.isEmpty(status) || !ProductStatusEnum.contains(status)) {
            log.warn("收到到无效的状态：" + (StringUtils.isEmpty(status)?"null": status));
            return;
        }
        SocialProductUser productUser = productUserService.selectSocialProductUser(userId, id);
        // 兼容处理 一般情况下不会出现
        if (StringUtils.isNull(productUser)) {
            productUser = new SocialProductUser();
            productUser.setProductId(product.getId());
            productUser.setUserId(userId);
            productUser.setProductUrl(productUser.getProductUrl());
            productUser.setStatus(product.getStatus());
            productUserService.insertSocialProductUser(productUser);
        }

        // 更新商品数据
        if (Objects.equals(status, ProductStatusEnum.success.toString())) {
            processorProduct(userId, new RequestFullItem(jsonObject.getObject("data", JSONObject.class)));
        } else {
            if (!Objects.equals(product.getStatus(), ProductStatusEnum.success.toString())) {
                product.setStatus(status);
                updateSocialProduct(product);
            }
        }
        // 更新用户数据状态
        productUser.setStatus(status);
        if (Objects.equals(status, ProductStatusEnum.error.toString())) {
            String error = jsonObject.getString("message");
            productUser.setErrorMsg(error);
        }
        productUserService.updateSocialProductUser(productUser);

    }

    private void changePoint(String productId, VideoPoints points ) {
        pointsService.changPoint(points, 0 - SystemPointConfig.PRODUCT_POINT, "Product_Use:"+productId);
    }
    // 解析更新数据
    public void processorProduct(Long userId, RequestFullItem item) {
        // 更新shop
        SocialShop shop = item.getShop();
        if (StringUtils.isNotNull(shop)) {
            SocialShop oldShop = shopService.selectSocialShopByOutId(shop.getShopOutid());
            shop.setStatus(ProductStatusEnum.success.toString());
            if (StringUtils.isNotNull(oldShop)) {
                shop.setId(oldShop.getId());
                shopService.updateSocialShop(shop);
            } else {
                shopService.insertSocialShop(shop);
            }
            SocialShopUser shopUser = shopUserService.selectSocialShopUserByUserId(userId, shop.getId());
            if (StringUtils.isNull(shopUser)) {
                shopUser = new SocialShopUser();
                shopUser.setShopId(shop.getId());
                shopUser.setUserId(userId);
                shopUser.setShopOutid(shop.getShopOutid());
                shopUserService.insertSocialShopUser(shopUser);
            }
        }

        // 更新商品
        SocialProduct product = item.getProduct();
        product.setProductInfoUpdateBy(userId);
        product.setShopId(shop.getId());
        SocialProduct oldProduct = socialProductMapper.selectSocialProductByOutId(product.getProductOutid());
        product.setId(oldProduct.getId());
        product.setStatus(ProductStatusEnum.success.toString());
        product.setProductLink(oldProduct.getProductLink());
        updateSocialProduct(product);

        // 更新商品销售趋势
        List<SocialProductTrend> trendList = product.getTrends();
        if (!trendList.isEmpty()) {
            productTrendService.updateTrendByProduct(trendList, product);
        }

        // 更新视频
        List<SocialVideo> videoList = item.getVideoList();
        if (!videoList.isEmpty()) {
            videoService.updateVideoList(userId, videoList, product);
        }

        // 跟新kol
        List<SocialKol> kolList = item.getKolList();
        if (!kolList.isEmpty()) {
            kolService.updateKolList(userId, kolList, product);
        }
    }


    /**
     * 查询商品数据列表
     * 
     * @param socialProduct 商品数据
     * @return 商品数据
     */
    @Override
    public List<SocialProduct> selectSocialProductList(SocialProduct socialProduct)
    {
        return socialProductMapper.selectSocialProductList(socialProduct);
    }

    /**
     * 根据用户查询查询商品数据列表
     *
     * @param socialProduct 商品数据
     * @param userId
     * @return 商品数据集合
     */
    @Override
    public List<SocialProduct> selectSocialProductList(SocialProduct socialProduct, Long userId) {
        return socialProductMapper.selectSocialProductListByUserId(socialProduct, userId);
    }


    /**
     * 新增商品数据
     * 
     * @param socialProduct 商品数据
     * @return 结果
     */
    @Override
    public int insertSocialProduct(SocialProduct socialProduct)
    {
        return socialProductMapper.insertSocialProduct(socialProduct);
    }

    /**
     * 修改商品数据
     * 
     * @param socialProduct 商品数据
     * @return 结果
     */
    @Override
    public int updateSocialProduct(SocialProduct socialProduct)
    {
        return socialProductMapper.updateSocialProduct(socialProduct);
    }

    /**
     * 批量删除商品数据
     * 
     * @param ids 需要删除的商品数据主键
     * @return 结果
     */
    @Override
    public int deleteSocialProductByIds(Long[] ids)
    {
        return socialProductMapper.deleteSocialProductByIds(ids);
    }

    /**
     * 删除商品数据信息
     * 
     * @param id 商品数据主键
     * @return 结果
     */
    @Override
    public int deleteSocialProductById(Long id)
    {
        return socialProductMapper.deleteSocialProductById(id);
    }
}
